import {ipcRenderer} from "electron";

const fs = require("fs")
const path = require('path')
const fse = require('fs-extra')


/**
 * 临时数据库
 * @param key
 * @param value
 */
export const setParamsHandle = (key, value) => {
    ipcRenderer.invoke("set-params", key, value).then(async res => {
        console.log(res)
    }).catch(err => {
        console.log(err)
    })
}

/**
 * 临时数据库获取
 * @param key
 */
export const getParamsHandle = (key) => {
    return new Promise((resolve, reject) => {
        ipcRenderer.invoke("get-params", key).then(async res => {
            // 备份文件保存路径
            resolve(res)
        }).catch(err => {
            console.log(err)
        })
    })
}

/**
 * 本地文件读取
 * @param src:本地文件完整路径
 * @returns {Promise<unknown>}
 */
export const readFileHandle = (src) => {
    return new Promise(function (resolve, reject) {
        fs.readFile(src, (err, bytesRead) => {
            if (err) throw err;
            const baseName = path.basename(src)
            const sps = baseName.split('.')
            const arrayBuffer = new Uint8Array(bytesRead).buffer
            const fileType = `image/${sps[sps.length - 1]}`
            const blobF = new Blob([arrayBuffer], {type: fileType});
            blobF.name=baseName
            resolve({name: baseName, path: src, type: fileType, blob: blobF});
        });
    })
}

/**
 * @param src:源路径，完整路径
 * @param dest:移动目标路径，包含文件名
 * @returns {Promise<>}
 */
export const moveFileHandle = (src, dest) => {
    return new Promise(function (resolve, reject) {
        fse.pathExists(src, (err, exists) => {
            if (exists) {
                const baseDir = path.dirname(dest)
                fse.ensureDir(baseDir)
                fse.move(src, dest, err => {
                    if (err) {
                        resolve({code: 400, msg: `${dest}存在同名文件`})
                    }
                })
            } else {
                resolve({code: 400, msg: `${src}文件不存在`});
            }
        })
    })
}

/**
 * @param src:源路径，完整路径
 * @returns {Promise<Promise>}
 */
export const removeFileHandle = (src) => {
    return new Promise(function (resolve, reject) {
        const isExit = fs.existsSync(src)
        if (isExit) {
            fse.removeSync(src)
        }
        resolve()
    })
}

/**
 * @param src:源路径，扫描文件夹路径
 * @param exts<Array>: 允许文件类型，例：['.png', '.jpg'] ,空值默认所有
 * @returns {Promise<Array>}
 */
export const fileListHandle = async (src, exts = []) => {
    let fullFiles = []
    const fileExist = await fse.pathExists(src)
    if (fileExist) {
        const files = fs.readdirSync(src,)
        for (const filename of files) {
            const fullFilePath = path.join(src, filename) //完整路径
            const stats = fs.statSync(fullFilePath)
            const isFile = stats.isFile()
            const isDir = stats.isDirectory()
            const extName = path.extname(fullFilePath)
            if (isFile) {
                if (exts instanceof Array && exts.length !== 0) {
                    if (exts.indexOf(extName) !== -1) {
                        fullFiles.push(fullFilePath)
                    }
                } else {
                    fullFiles.push(fullFilePath)
                }
            }
            if (isDir) {
                const obsPath = await fileListHandle(fullFilePath, exts)
                fullFiles = [...fullFiles, ...obsPath]
            }
        }
    }
    return fullFiles
}



